import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { withMiddleware } from "@/lib/middleware/entry";
import { CreateMenuRequest } from "@/types/menu";

async function handlePost(req: NextRequest) {
  const { name, path, order, isActive, parentId, iconFileId, sysCode } = (await req.json()) as CreateMenuRequest;

  const data: any = {
    name,
    path,
    order: order ? Number(order) : 0,
    isActive: isActive,
    iconFile: {
      connect: {
        id: iconFileId,
      },
    },
    sysCode,
  };

  if (parentId) {
    data.parent = {
      connect: {
        id: parentId,
      },
    };
  }

  const menu = await prisma.menu.create({
    data,
  });

  return { data: menu };
}

export const POST = withMiddleware(handlePost);